package utils

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"net/http"
)

type HttpServer struct {
	Auth string
}

func InitHttp() *HttpServer {
	return &HttpServer{}
}

func (h *HttpServer) Do(httpType string, url string, body []byte, auth bool, header map[string]string) ([]byte, error) {

	payload := bytes.NewBufferString(string(body))
	req, err := http.NewRequest(httpType, url, payload)
	if err != nil {
		return nil, err
	}
	if len(header) > 0 {
		for k, v := range header {
			req.Header.Set(k, v)
		}
	}
	if auth {
		req.Header.Set("Authorization", "Bearer "+h.Auth)
	}
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	res, err := io.ReadAll(resp.Body)
	fmt.Println("[http]请求结果", string(res))
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != 200 {
		return nil, errors.New(string(res))
	}
	return res, nil
}

func (h *HttpServer) SetAuth(auth string) {
	h.Auth = auth
}
